package com.heima.reggie.controller;

import com.heima.reggie.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Api(tags = "文件上传下载")
public class FileController {
    @Value("${reggie_path}")
    private String directory;

    @ApiOperation(value ="文件上传")
    @PostMapping("/common/upload")
    public R upload(MultipartFile file) {

        //构建新的文件名称
        String preffix = UUID.randomUUID().toString().replace("-", "");
        //获取原来的这个文件的后缀名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //组装成新的文件名称
        String newName=preffix+substring;
        //构建一个文件指向位置,然后把临时文件
        File f = new File(directory);
        if (!f.exists()) {
            f.mkdirs();
        }
        try {
            file.transferTo(new File(directory,newName));
            return R.success(newName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败！");
        }
    }
    @ApiOperation(value ="文件下载")
    @GetMapping("/common/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream inputStream=new FileInputStream(directory+name);
            //输出流，通过输出流将文件写会服务器
            ServletOutputStream outputStream=response.getOutputStream();

            response.setContentType("image/jpg");

            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
